<template>
  <div>
    <basic-container>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="10">
<!--          <div class="user__tree boxsty">-->
<!--            <el-input placeholder="输入关键字进行过滤" v-model="filterText" clearable></el-input>-->
<!--            <el-tree ref="tree" :data="treeData" :props="defaultProps" :filter-node-method="filterNode"-->
<!--                     class="filter-tree" node-key="id" highlight-current :default-expanded-keys="[1]" accordion-->
<!--                     @node-click="getNodeData"/>-->
<!--          </div>-->
          <div class="user__tree boxsty">
            <avue-tree :option="treeOption" :data="treeData" @node-click="getNodeData">
              <span class="el-tree-node__label" slot-scope="{ node, data }">
                <el-tooltip class="item" effect="dark" content="无数据权限" placement="right-start" v-if="data.isLock">
                  <span>{{ node.label }} <i class="el-icon-lock"></i></span>
                </el-tooltip>
                <span v-if="!data.isLock">
                  <span v-if="data.isRecord">{{ node.label }} <i class="el-icon-check"></i></span>
                  <span v-else>{{ node.label }}</span>
                </span>
              </span>
            </avue-tree>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="14">
          <div class="user__main boxsty filter-container" >
            <div class="box-card">

              <el-form ref="dataForm" :rules="rules" label-position="left"  :model="dataForm" label-width="160px">
                <el-form-item label="部门名称" prop="jgDeptName">
                  {{dataForm.jgDeptName}}
                </el-form-item>

                <el-form-item label="部门全称" prop="deptAllName">
                    {{dataForm.deptAllName}}
                </el-form-item>

                <el-form-item label="机构奖金标识" prop="jgJjFlag">
                  <el-radio-group v-model="dataForm.jgJjFlag">
                    <el-radio :label="'是'">是</el-radio>
                    <el-radio :label="'否'">否</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-row>
                  <el-col :span="20">
                    <el-form-item label="奖金管理员" prop="jgGlUserName">
                      <el-input v-model="dataForm.jgGlUserName" :disabled="true" placeholder="请选择奖金管理员"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    &nbsp;<el-button @click="selectCheckUser('奖金')">选择</el-button>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="20">
                    <el-form-item label="机构负责人" prop="jgFzUserName">
                      <el-input v-model="dataForm.jgFzUserName" :disabled="true" placeholder="请选择机构负责人"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4">
                    &nbsp;<el-button @click="selectCheckUser('机构')">选择</el-button>
                  </el-col>
                </el-row>
                <el-form-item label="资金项说明" prop="jgJjsm">
                  <el-input v-model="dataForm.jgJjsm" type="textarea"  :rows="2" placeholder=""/>
                </el-form-item>
              </el-form>

              <span slot="footer" class="dialog-footer" style="float: right">
                <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit">保存</el-button>
                <el-button @click="clearDataList">重置</el-button>
              </span>
            </div>
          </div>
        </el-col>
      </el-row>
    </basic-container>
    <!--奖金管理员-->
    <check-user-role ref="checkUserRole" :multiple='false' :roleCode="roleCode" :userIds='userRoleIds' @getUserList="getUserRoleList"></check-user-role>
    <!--机构负责人-->
    <check-user-all ref="checkUserAll" :multiple='false' :roleCode="roleCode" :userIds='userAllIds' @getUserList="getUserAllList"></check-user-all>
  </div>
</template>

<script>
import {getJjjgwhList,getJjListRecordByDeptId,getJjListByDeptId, addObj, putObj} from '@/api/jiangjin/jiangjinjjjgwh'
import { delObj, fetchTree, getObj } from '@/api/admin/dept'
import checkUserRole from '@/components/form/compound/selectUser'
import checkUserAll from '@/components/form/compound/selectUser'


export default {
  components:{
    checkUserRole,
    checkUserAll
  },
  data () {
    return {
      canSubmit: true,
      filterText: "",
      treeData: [],
      // defaultProps: {
      //   children: 'children',
      //   label: 'name'
      // },
      treeOption: {
        nodeKey: 'id',
        addBtn: false,
        menu: false,
        props: {
          label: 'name',
          value: 'id'
        }
      },
      listQuery:'',

      roleCode:'',
      userRoleIds:[],
      userAllIds:[],
      jjjgwhList:[],//奖金机构list

      dataForm: {
        jgDeptId:'',
        jgDeptName:'',
        jgJjFlag:'否', //机构奖金标识,
        jgGlUserId:'',
        jgGlUserName:'',
        jgFzUserId:'',
        jgFzUserName:'',
        jgJjsm:'',
        deptId:'',
        deptAllName:''
      },

      rules: {
        //jgDeptName: [{ required: true, message: '请选择部门', trigger: 'blur' }]
        jgGlUserName: [
          { required: true, message: '奖金管理员不能为空', trigger: 'blur' }
        ],
        // jgFzUserName: [
        //   { required: true, message: '机构负责人不能为空', trigger: 'blur' }
        // ],
      }

    }
  },
  created() {
    this.getList();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    init () {
      this.clearDataList();
    },
    //清空记录
    clearDataList(){
      // this.roleCode = '';
      this.userRoleIds = [];
      this.userAllIds = [];
      this.initNull();
      this.$refs['dataForm'].resetFields()
    },
    //对树节点进行筛选时执行的方法
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    //单击节点事件
    getNodeData(data){
      // 后台查询数据库（现在采用一次取后js查询刷新)
      // getJjListRecordByDeptId(data.id).then( res => {
      //  //console.log(res.data.data);
      // })
      ////console.log(data);
      // return;

      this.clearDataList();

      if(data.isLock){
        return;
      }
      getJjListByDeptId(data.id).then( ress => {
        const cress =ress.data.data;
        if(cress.length !== 0){
          this.dataForm = cress[0];
        }
        //目的是取得全称
        getObj(data.id).then(res => {
          const tData =  res.data.data;

          this.$set(this.dataForm,'jgDeptId',tData.deptId);
          this.$set(this.dataForm,'jgDeptName',tData.name);

          this.$set(this.dataForm,'deptId',tData.deptId);
          this.$set(this.dataForm,'deptAllName',tData.deptName);

          // this.dataForm["jgDeptId"] = tData.deptId;
          // this.dataForm["jgDeptName"] = tData.name;
          // this.dataForm["deptId"] = tData.deptId;
          // this.dataForm["deptAllName"] = tData.deptName;
        })
      })
    },
    getList() {
      // fetchTree(this.listQuery).then(response => {
      //   this.treeData = response.data.data
      // })

      fetchTree(this.listQuery).then(response => {
        const cData = response.data.data;

        getJjjgwhList().then(res => {
          this.jjjgwhList = [];
          this.jjjgwhList = res.data.data;

          this.treeData = this.getNewArray(cData)
        })

        ////console.log(this.getNewArray(cData));
        // this.treeData = this.getNewArray(cData)
      })
    //
    },

    //是否有记录
    recordExist(deptId,cJjList){
      let bResult = false;
      cJjList.find(value => {
        if (deptId === value.jgDeptId) {
          bResult = true;
        }
      })
      return bResult;
    },

    //为数组添加新属性
    getNewArray(vData){
      let nStr= [];

      for(let i=0; i<vData.length ;i++){
        if(vData[i].children.length === 0){
          nStr.push({
            id: vData[i].id,
            isLock: vData[i].isLock,
            name: vData[i].name,
            parentId: vData[i].parentId,
            isRecord: this.recordExist(vData[i].id,this.jjjgwhList),
              // Math.ceil(Math.random()*1000),
            children: vData[i].children,
          })
        }
        else {
          nStr.push({
            id: vData[i].id,
            isLock: vData[i].isLock,
            name: vData[i].name,
            parentId: vData[i].parentId,
            isRecord: this.recordExist(vData[i].id,this.jjjgwhList),
            children: this.getNewArray(vData[i].children),
          })
        }
      }

      return nStr;
    }
    ,
    //取得角色用户-奖金管理
    getUserRoleList(data){
      if(data.length === 0){
        this.$set(this.dataForm,'jgGlUserId',"")
        this.$set(this.dataForm,'jgGlUserName',"")
        // return;
      }else {
        this.$set(this.dataForm,'jgGlUserId',data[0].userId)
        this.$set(this.dataForm,'jgGlUserName',data[0].ryName)
      }
    },
    //取得所有用户
    getUserAllList(data){
      if(data.length === 0){
        this.$set(this.dataForm,'jgFzUserId',"")
        this.$set(this.dataForm,'jgFzUserName',"")
        //return;
      }else {
        this.$set(this.dataForm,'jgFzUserId',data[0].userId)
        this.$set(this.dataForm,'jgFzUserName',data[0].ryName)
      }
    },
    selectCheckUser(vm){
      if(this.dataForm.jgDeptId === ""){
        this.$notify.closeAll();
        this.$notify.error('请先在左侧选择部门');
        return;
      }

      if(vm === "奖金"){
        this.roleCode = "JJ_SALARYADMIN";
        this.userRoleIds = [];
        this.userRoleIds.push(this.dataForm.jgGlUserId);
        this.userAllIds = [];
        //防止数据慢于页面加载
        this.$nextTick(()=>{
          this.$refs.checkUserRole.init();
        })

      }else{
        this.roleCode = "";
        this.userRoleIds = [];
        this.userAllIds = [];
        this.userAllIds.push(this.dataForm.jgFzUserId);
        this.$nextTick(()=>{
          this.$refs.checkUserAll.init();
        })

      }
    },

    //=================================
    //初始化清空
    initNull(){
      this.dataForm = {
        jgDeptId:'',
        jgDeptName:'',
        jgJjFlag:'否', //机构奖金标识,
        jgGlUserId:'',
        jgGlUserName:'',
        jgFzUserId:'',
        jgFzUserName:'',
        jgJjsm:'',
        deptId:'',
        deptAllName:''
      };
    },

    // 表单提交
    dataFormSubmit () {
      if(this.dataForm.jgDeptId === ""){
        this.$notify.closeAll();
        this.$notify.error('请先在左侧选择部门');
        return;
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          if (this.dataForm.id) {
            putObj(this.dataForm).then(data => {
              this.$notify.success('修改成功');
              this.clearDataList();
              this.getList();
              this.canSubmit = true;
            }).catch(() => {
              this.canSubmit = true;
            });
          } else {
            addObj(this.dataForm).then(data => {
              this.$notify.success('添加成功');
              this.clearDataList();
              this.getList();
              this.canSubmit = true;
            }).catch(() => {
              this.canSubmit = true;
            });
          }
        }
      })
    }

  }
}
</script>
